<template>
  <div class="statistic-analysis-container">
    <el-row :gutter="20">
      <!-- 数据概览卡片 -->
      <el-col :span="24">
        <div class="overview-section">
          <el-card class="overview-card">
            <template #header>
              <div class="card-header">
                <h3>数据概览</h3>
                <el-button type="primary" @click="refreshData" :loading="isLoading">
                  <el-icon><Refresh /></el-icon> 刷新数据
                </el-button>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="8">
                <div class="data-item">
                  <el-icon class="data-icon building"><House /></el-icon>
                  <div class="data-info">
                    <div class="data-label">建筑物总数</div>
                    <div class="data-value">{{ buildingCount }}</div>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="8">
                <div class="data-item">
                  <el-icon class="data-icon facility"><Service /></el-icon>
                  <div class="data-info">
                    <div class="data-label">设施总数</div>
                    <div class="data-value">{{ facilityCount }}</div>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="8">
                <div class="data-item">
                  <el-icon class="data-icon road"><Guide /></el-icon>
                  <div class="data-info">
                    <div class="data-label">道路总数</div>
                    <div class="data-value">{{ roadCount }}</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>

      <!-- 建筑物类型分布 -->
      <el-col :xs="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>建筑物类型分布</h3>
            </div>
          </template>
          <div class="chart-container" ref="buildingChartRef"></div>
        </el-card>
      </el-col>

      <!-- 设施类型分布 -->
      <el-col :xs="24" :md="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>设施类型分布</h3>
            </div>
          </template>
          <div class="chart-container" ref="facilityChartRef"></div>
        </el-card>
      </el-col>

      <!-- 道路类型统计 -->
      <el-col :xs="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h3>道路类型统计</h3>
            </div>
          </template>
          <div class="chart-container" ref="roadChartRef"></div>
        </el-card>
      </el-col>

      <!-- 数据表格 -->
      <el-col :span="24">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <h3>详细数据</h3>
              <el-radio-group v-model="activeTable" size="small">
                <el-radio-button label="building">建筑物</el-radio-button>
                <el-radio-button label="facility">设施</el-radio-button>
                <el-radio-button label="road">道路</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <!-- 建筑物表格 -->
          <el-table
            v-if="activeTable === 'building'"
            :data="buildingTableData"
            stripe
            style="width: 100%"
            v-loading="isLoading"
          >
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="description" label="描述" />
          </el-table>

          <!-- 设施表格 -->
          <el-table
            v-if="activeTable === 'facility'"
            :data="facilityTableData"
            stripe
            style="width: 100%"
            v-loading="isLoading"
          >
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="description" label="描述" />
          </el-table>

          <!-- 道路表格 -->
          <el-table
            v-if="activeTable === 'road'"
            :data="roadTableData"
            stripe
            style="width: 100%"
            v-loading="isLoading"
          >
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="type" label="类型" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { House, Service, Guide, Refresh } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query'
import * as echarts from 'echarts'

// 图层URL
const buildingLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/0'
const facilitiesLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/1'
const roadsLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/2'

// 图层实例
let buildingLayer: __esri.FeatureLayer | null = null
let facilitiesLayer: __esri.FeatureLayer | null = null
let roadsLayer: __esri.FeatureLayer | null = null

// 图表引用
const buildingChartRef = ref<HTMLElement | null>(null)
const facilityChartRef = ref<HTMLElement | null>(null)
const roadChartRef = ref<HTMLElement | null>(null)

// 图表实例
let buildingChart: echarts.ECharts | null = null
let facilityChart: echarts.ECharts | null = null
let roadChart: echarts.ECharts | null = null

// 数据状态
const isLoading = ref(false)
const buildingCount = ref(0)
const facilityCount = ref(0)
const roadCount = ref(0)

// 表格相关
const activeTable = ref('building')
const buildingTableData = ref<any[]>([])
const facilityTableData = ref<any[]>([])
const roadTableData = ref<any[]>([])

// 建筑物类型数据
const buildingTypeData = ref<{ name: string; value: number }[]>([])

// 设施类型数据
const facilityTypeData = ref<{ name: string; value: number }[]>([])

// 道路类型数据
const roadTypeData = ref<{ name: string; value: number }[]>([])

// 初始化图层
const initLayers = () => {
  // 创建建筑物图层 - 使用填充样式
  buildingLayer = new FeatureLayer({
    url: buildingLayerUrl,
    outFields: ['*'],
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-marker',
        color: [255, 165, 0, 0.6], // 橙色半透明
        outline: {
          color: [255, 140, 0, 1], // 深橙色边框
          width: 2
        }
      }
    } as any,
    popupTemplate: {
      title: '建筑物信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'name', label: '建筑名称' },
            { fieldName: 'BuildingType', label: '建筑类型' },
            { fieldName: 'OBJECTID', label: 'ID' }
          ]
        }
      ]
    }
  })

  // 创建设施图层 - 使用点样式
  facilitiesLayer = new FeatureLayer({
    url: facilitiesLayerUrl,
    outFields: ['*'],
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-marker',
        color: [0, 150, 255, 0.8], // 蓝色
        size: 12,
        outline: {
          color: [0, 100, 200, 1], // 深蓝色边框
          width: 2
        },
        style: 'circle'
      }
    } as any,
    popupTemplate: {
      title: '设施信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'name', label: '设施名称' },
            { fieldName: 'FacilityType', label: '设施类型' },
            { fieldName: 'OBJECTID', label: 'ID' }
          ]
        }
      ]
    }
  })

  // 创建道路图层 - 使用线样式，根据道路类型设置不同颜色
  roadsLayer = new FeatureLayer({
    url: roadsLayerUrl,
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'unique-value',
      field: 'RoadType',
      defaultSymbol: {
        type: 'simple-line',
        color: [128, 128, 128, 0.8], // 灰色默认
        width: 3
      },
      uniqueValueInfos: [
        {
          value: '主干道',
          symbol: {
            type: 'simple-line',
            color: [255, 0, 0, 0.9], // 红色
            width: 6
          }
        },
        {
          value: '次干道',
          symbol: {
            type: 'simple-line',
            color: [255, 165, 0, 0.8], // 橙色
            width: 4
          }
        },
        {
          value: '支路',
          symbol: {
            type: 'simple-line',
            color: [255, 255, 0, 0.8], // 黄色
            width: 3
          }
        },
        {
          value: '步行道',
          symbol: {
            type: 'simple-line',
            color: [0, 255, 0, 0.8], // 绿色
            width: 2,
            style: 'dash'
          }
        },
        {
          value: '自行车道',
          symbol: {
            type: 'simple-line',
            color: [0, 191, 255, 0.8], // 天蓝色
            width: 2,
            style: 'dot'
          }
        }
      ]
    } as any,
    popupTemplate: {
      title: '道路信息',
      content: [
        {
          type: 'fields',
          fieldInfos: [
            { fieldName: 'name', label: '道路名称' },
            { fieldName: 'RoadType', label: '道路类型' },
            { fieldName: 'OBJECTID', label: 'ID' }
          ]
        }
      ]
    }
  })
}

// 初始化图表
const initCharts = () => {
  // 初始化建筑物类型图表
  if (buildingChartRef.value) {
    buildingChart = echarts.init(buildingChartRef.value)
    buildingChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: []
      },
      series: [
        {
          name: '建筑物类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: []
        }
      ]
    })
  }

  // 初始化设施类型图表
  if (facilityChartRef.value) {
    facilityChart = echarts.init(facilityChartRef.value)
    facilityChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: [],
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '设施数量',
          type: 'bar',
          barWidth: '60%',
          data: []
        }
      ]
    })
  }

  // 初始化道路类型图表
  if (roadChartRef.value) {
    roadChart = echarts.init(roadChartRef.value)
    roadChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [],
          type: 'line',
          smooth: true,
          areaStyle: {}
        }
      ]
    })
  }
}

// 查询建筑物数据
const queryBuildingData = async () => {
  if (!buildingLayer) return

  try {
    // 查询所有建筑物
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = false

    const results = await buildingLayer.queryFeatures(query)
    const features = results.features

    // 更新建筑物总数
    buildingCount.value = features.length

    // 处理建筑物类型数据
    const typeMap = new Map<string, number>()

    // 处理表格数据
    buildingTableData.value = features.map(feature => {
      const attrs = feature.attributes
      const type = attrs.Buildingtype || '未知'

      // 统计类型数量
      typeMap.set(type, (typeMap.get(type) || 0) + 1)

      return {
        name: attrs.name || '未命名建筑',
        type: type,
        description: attrs.description || '无描述'
      }
    })

    // 转换为图表数据格式
    buildingTypeData.value = Array.from(typeMap.entries()).map(([name, value]) => ({
      name,
      value
    }))

    // 更新图表
    if (buildingChart) {
      buildingChart.setOption({
        legend: {
          data: buildingTypeData.value.map(item => item.name)
        },
        series: [
          {
            data: buildingTypeData.value
          }
        ]
      })
    }
  } catch (error) {
    console.error('查询建筑物数据失败', error)
    ElMessage.error('查询建筑物数据失败')
  }
}

// 查询设施数据
const queryFacilityData = async () => {
  if (!facilitiesLayer) return

  try {
    // 查询所有设施
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = false

    const results = await facilitiesLayer.queryFeatures(query)
    const features = results.features

    // 更新设施总数
    facilityCount.value = features.length

    // 处理设施类型数据
    const typeMap = new Map<string, number>()

    // 处理表格数据
    facilityTableData.value = features.map(feature => {
      const attrs = feature.attributes
      const type = attrs.FacilitiesType || '未知'

      // 统计类型数量
      typeMap.set(type, (typeMap.get(type) || 0) + 1)

      return {
        name: attrs.name || '未命名设施',
        type: type,
        description: attrs.description || '无描述'
      }
    })

    // 转换为图表数据格式
    facilityTypeData.value = Array.from(typeMap.entries()).map(([name, value]) => ({
      name,
      value
    }))

    // 更新图表
    if (facilityChart) {
      facilityChart.setOption({
        xAxis: [
          {
            data: facilityTypeData.value.map(item => item.name)
          }
        ],
        series: [
          {
            data: facilityTypeData.value.map(item => item.value)
          }
        ]
      })
    }
  } catch (error) {
    console.error('查询设施数据失败', error)
    ElMessage.error('查询设施数据失败')
  }
}

// 查询道路数据
const queryRoadData = async () => {
  if (!roadsLayer) return

  try {
    // 查询所有道路
    const query = new Query()
    query.where = '1=1'
    query.outFields = ['*']
    query.returnGeometry = false

    const results = await roadsLayer.queryFeatures(query)
    const features = results.features

    // 更新道路总数
    roadCount.value = features.length

    // 处理道路类型数据
    const typeMap = new Map<string, number>()

    // 处理表格数据
    roadTableData.value = features.map(feature => {
      const attrs = feature.attributes
      const type = attrs.RoadType || '未知'

      // 统计类型数量
      typeMap.set(type, (typeMap.get(type) || 0) + 1)

      return {
        name: attrs.name || '未命名道路',
        type: type
      }
    })

    // 转换为图表数据格式
    roadTypeData.value = Array.from(typeMap.entries()).map(([name, value]) => ({
      name,
      value
    }))

    // 更新图表
    if (roadChart) {
      roadChart.setOption({
        xAxis: {
          data: roadTypeData.value.map(item => item.name)
        },
        series: [
          {
            data: roadTypeData.value.map(item => item.value)
          }
        ]
      })
    }
  } catch (error) {
    console.error('查询道路数据失败', error)
    ElMessage.error('查询道路数据失败')
  }
}

// 刷新所有数据
const refreshData = async () => {
  isLoading.value = true
  try {
    await Promise.all([
      queryBuildingData(),
      queryFacilityData(),
      queryRoadData()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败', error)
    ElMessage.error('刷新数据失败')
  } finally {
    isLoading.value = false
  }
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  buildingChart?.resize()
  facilityChart?.resize()
  roadChart?.resize()
}

// 组件挂载时初始化
onMounted(async () => {
  // 初始化图层
  initLayers()

  // 初始化图表
  initCharts()

  // 加载数据
  await refreshData()

  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 销毁图表实例
  buildingChart?.dispose()
  facilityChart?.dispose()
  roadChart?.dispose()

  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)

  // 清空图层引用
  buildingLayer = null
  facilitiesLayer = null
  roadsLayer = null
})
</script>

<style scoped>
.statistic-analysis-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.overview-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.data-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: 100%;
  min-height: 80px;
}

.data-icon {
  font-size: 36px;
  margin-right: 16px;
  padding: 10px;
  border-radius: 50%;
  background-color: rgba(64, 158, 255, 0.1);
}

.data-icon.building {
  color: #409EFF;
}

.data-icon.facility {
  color: #67C23A;
}

.data-icon.road {
  color: #E6A23C;
}

.data-info {
  flex: 1;
}

.data-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-card,
.table-card,
.overview-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-container {
  height: 300px;
  width: 100%;
}

@media (max-width: 768px) {
  .data-item {
    margin-bottom: 10px;
  }

  .chart-container {
    height: 250px;
  }
}
</style>
